/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jmooc.soap;

import com.jmooc.entity.Course;
import com.jmooc.entity.ReadCourse;
import com.jmooc.entity.User;
import com.jmooc.service.CourseService;
import com.jmooc.service.ReadCourseService;
import com.jmooc.service.UserService;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;

/**
 *
 * @author Group
 */
@WebService(serviceName = "soap/courses")
public class CourseWebService {
    
    @EJB
    private CourseService courseService;
    
    @EJB
    private UserService userService;
    
    @EJB
    private ReadCourseService readCourseService;
    
    @WebMethod(operationName = "getAllCourses")
    public List<Course> getAllCourses(@WebParam(name = "token") String token) {
        User user = userService.getUserByToken(token);
        
        if (user == null)
            return null;
        
        return courseService.getAllCourses();
    }

    @WebMethod(operationName = "getById")
    public Course getById(@WebParam(name = "token") String token, @WebParam(name = "id") Long id) {
        User user = userService.getUserByToken(token);
        
        if (user == null)
            return null;
        
        return courseService.getById(id);
    }

    @WebMethod(operationName = "takeCourse")
    public boolean takeCourse(@WebParam(name = "token") String token, @WebParam(name = "courseId") Long courseId) {
        User user = userService.getUserByToken(token);
        
        if (user == null)
            return false;
        
        Course course = courseService.getById(courseId);
        
        // Si c'est là première fois qu'une personne suit le cours, on l'enregistre dans ses cours
        if (!readCourseService.isUserAlreadyReadingACourse(user, course)) {
            ReadCourse rc = new ReadCourse();
            rc.setCourse(course);
            rc.setUser(user);
            rc.setReadingDate(new Date());
            readCourseService.create(rc);
        }
        
        return true;
    }
    
}
